import { Injectable } from '@nestjs/common';
import { CreateCartDto } from './dto/create-cart.dto';
import { UpdateCartDto } from './dto/update-cart.dto';
import { Cart } from './entities/cart.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class CartService {
  constructor(
    @InjectRepository(Cart)
    private readonly cartRepository: Repository<Cart>,
  ) {}

  create(createCartDto: CreateCartDto) {
    return 'This action adds a new cart';
  }

  findAll() {
    return `This action returns all cart`;
  }

  async findAllCartByUserId(
    userId: number,
    currentPage: number,
    pageSize: number,
  ): Promise<Array<Cart> | any> {
    const list = await this.cartRepository.findAndCount({
      select: ['id', 'type', 'car', 'user', 'service'],
      relations: ['car', 'user', 'service', 'service.photos'],
      skip: (currentPage - 1) * pageSize,
      take: pageSize,
      where: { user: { id: userId }, isDelete: false },
      order: { id: 'DESC' },
    });

    const result = list[0].map((item) => {
      return {
        ...item,
        car: {
          id: item.car.id,
          primaryId: item.car.primary_id,
          license_plate: item.car.license_plate,
          brand: item.car.brand,
          status: item.car.status,
        },
        user: {
          id: item.user.id,
          primaryId: item.user.primary_id,
          name: item.user.name,
        },
        service: {
          id: item.service.id,
          primaryId: item.service.primary_id,
          category: item.service.category,
          service_point: item.service.service_point,
          money: item.service.money,
          photo: item.service.photos[0] || {},
        },
      };
    });

    return {
      list: result,
      totalCount: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} cart`;
  }

  update(id: number, updateCartDto: UpdateCartDto) {
    return `This action updates a #${id} cart`;
  }

  remove(id: number) {
    return `This action removes a #${id} cart`;
  }
}
